<?php
namespace app\home;

use pidan\App;
use pidan\Response;
use pidan\Validate;
use pidan\facade\Route;
use pidan\facade\Config;


/**
 * 控制器基础类
 */
abstract class Controller
{
    protected $request;

    protected $app;

    protected $batchValidate = false;

    protected $middleware = [];

    protected $assign = [];


    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct()
    {
        $this->initialize();

        $this->app=$app = app();$this->request=$request=$app->make('request');
        //$app->lang->load($app->getAppPath() . 'lang/' . $app->lang->getLangSet() . '/' . $app->http->getName() . '.php');//加载app_name语言包
    }


    // 初始化
    protected function initialize()
    {
    }

		protected function code($code,string $msg='',array $result=[]){
			return $this->result(['code'=>$code,'msg'=>$msg,'data'=>$result]);
		}

		protected function api($data,int $code=0,string $msg=''){
			return $this->result(['code'=>$code,'msg'=>$msg,'data'=>$data]);
		}
		protected function lists($data,$count,int $code=0,string $msg=''){
			return $this->result(['code'=>$code,'msg'=>$msg,'count'=>$count,'data'=>$data]);
		}


    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', $data = '', $type = 'html', string $url = null, int $wait = 3, array $header = [], int $code = 1){
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
        }
        $assign = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        // 把跳转模板的渲染下沉，这样在 response_send 行为里通过getData()获得的数据是一致性的格式
        if ('html' == strtolower($type)) {
            include config('jump.jump_tpl');
            $response = Response::create(ob_get_clean(), 'html')->header($header);
        } else {
            $response = Response::create($assign, $type)->header($header);
        }
        return $response;
    }

    protected function error($msg = '', $data = '', $type = 'html', string $url = null, int $wait = 3, array $header = [], int $code = 0){
        return $this->success($msg, $data, $type, $url, $wait, $header, $code);
    }

    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param integer $code 返回的code
     * @param mixed $msg 提示信息
     * @param string $type 返回数据格式
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function result($result, $type = 'json', array $header = []){
        return Response::create($result, $type)->header($header);
    }

    /**
     * URL重定向
     * @access protected
     * @param string $url 跳转的URL表达式
     * @param integer $code http code
     * @param array $with 隐式传参
     * @return void
     */
    protected function redirect($url, $code = 302, $with = []){
        return Response::create($url, 'redirect')->code($code)->with($with);
    }

    /**
     * @param array $data 验证数据
     * @param $validate   验证类
     * @param $scene   验证场景
     */
    public function validate(array $data, $validate, $scene = ''){
        try {
            $class = new $validate;
            if (!empty($scene)) {
                $res = $class->scene($scene)->check($data);
            } else {
                $res = $class->check($data);
            }
            if (!$res) {
                return error(-1, $class->getError());
            } else
                return success(1);

        } catch (\Exception $e) {
            return error(-1, $e->getMessage());
        }

    }
}
